package uiUtil;

import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultListSelectionModel;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;

public abstract class AbstractCustomTable <T> extends JTable implements
		CustomTableIF <T> {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

/////// Start of inner class
	private class CustomTableModel extends AbstractTableModel{
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		private List<T> model = new ArrayList<>();
		private String[] colNames = {};
		
		public void setModel(List<T> model) {
			
			//System.out.println("AbstractCustomTable.CustomTableModel.setModel()");
			this.model = model;
			super.fireTableDataChanged();
			
		}
		
		public void setColNames(String[] colNames) {
			
			this.colNames = colNames;
			super.fireTableStructureChanged();
			
		}
		
		@Override
		public String getColumnName(int column) {
			
			//System.out.println("AbstractCustomTable.CustomTableModel.getColumnName(" + column + ")");
			return this.colNames[column];
			
		}

		@Override
		public int getColumnCount() {
			
			//System.out.println("AbstractCustomTable.CustomTableModel.getColumnCount() --> " + colNames.length);
			return this.colNames.length;
			
		}

		@Override
		public int getRowCount() {
			
			//System.out.println("AbstractCustomTable.CustomTableModel.getRowCount() --> " + model.size() );
			return this.model.size();
			
		}

		@Override
		public Object getValueAt(int row, int col) {
			
			//System.out.println("AbstractCustomTable.CustomTableModel.getValueAt(" + row + ", " + col + ")");
			return getCellValue(col, model.get(row));
			
		}

		public T getObjectByIndex(int row) {
			
			return model.get(row);
			
		}
		
	}
/////// End of inner class
	
	private CustomTableModel tableModel;
	
	public AbstractCustomTable() {
		
		this.tableModel = new CustomTableModel();
		this.setModel(this.tableModel);
		super.setSelectionMode(DefaultListSelectionModel.SINGLE_SELECTION);
		
	}

	@Override
	public final void setModel(List<T> objectList) {
		
		this.tableModel.setModel(objectList);
		
	}

	
	public abstract Object getCellValue(int col, T o);

	@Override
	public final void setColNames(String... colNames) {
		
		this.tableModel.setColNames(colNames);
		
	}

	@Override
	public final T getSelectedObject() {
		
		int row = getSelectedRow();
		if (row < 0) {
			return null;
		}
		return this.tableModel.getObjectByIndex(row);
	}
	
}
